package com.demo.controller;
import com.demo.bean.vo.ResponseResult;
import com.demo.config.router.RouteHandler;
import com.demo.config.router.RouteRegistry;
import com.demo.util.JsonUtil;
import com.sun.net.httpserver.HttpExchange;
import com.sun.net.httpserver.HttpHandler;

import java.io.IOException;
import java.io.OutputStream;
import java.net.URI;
import java.util.HashMap;
import java.util.Map;

public class RequestRouter implements HttpHandler {
  private final RouteRegistry routeRegistry;

  public RequestRouter() {
    this.routeRegistry = new RouteRegistry();
    registerRoutes();
  }

  private void registerRoutes() {
    UserRouteHandler userHandler = new UserRouteHandler();

    // 注册用户相关路由
    routeRegistry.register("GET", "/user/selectAllUsers", userHandler::getAllUsers);
    routeRegistry.register("GET", "/user/selectUserByUserId", userHandler::getUserById);

    // 示例：注册其他路由
    // routeRegistry.register("POST", "/product/create", productHandler::createProduct);
  }

  @Override
  public void handle(HttpExchange exchange) throws IOException {
    URI uri = exchange.getRequestURI();
    Map<String, String> params = parseQueryParams(uri.getQuery());

    ResponseResult result;
    try {
      RouteHandler handler = routeRegistry.findHandler(exchange);

      if (handler != null) {
        result = handler.handle(params);
      } else {
        result = new ResponseResult(404, "Endpoint not found: " + uri.getPath(), null);
      }
    } catch (Exception e) {
      result = new ResponseResult(500, "Internal error: " + e.getMessage(), null);
      e.printStackTrace();
    }

    sendResponse(exchange, result);
  }

  private void sendResponse(HttpExchange exchange, ResponseResult result) throws IOException {
    String response = JsonUtil.toJson(result);
    exchange.getResponseHeaders().add("Content-Type", "application/json");
    exchange.sendResponseHeaders(result.getCode(), response.getBytes().length);

    try (OutputStream os = exchange.getResponseBody()) {
      os.write(response.getBytes());
    }
  }

  private Map<String, String> parseQueryParams(String query) {
    Map<String, String> params = new HashMap<>();
    if (query != null) {
      for (String param : query.split("&")) {
        String[] pair = param.split("=");
        if (pair.length > 1) {
          params.put(pair[0], pair[1]);
        }
      }
    }
    return params;
  }
}